package com.hqully.smartfumehood.shiro.realm;

import com.hqully.smartfumehood.common.enums.ResultEnum;
import com.hqully.smartfumehood.common.exception.ResultException;
import com.hqully.smartfumehood.entity.User;
import com.hqully.smartfumehood.service.UserService;
import com.hqully.smartfumehood.shiro.token.JWTToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * <p>
 *     对JWTToken进行检验，
 *     由JWTToken生成用户实体，
 *     对用户实体进行检验和授权
 * </p>
 * @author liulingyu
 * @date 2022-05-08 15:41
 * @version 1.0
 */
@Slf4j
public class JWTRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService  ;



    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.debug("JWTRealm 认证方法执行");

        JWTToken jwtToken = (JWTToken) token;

        String username = jwtToken.getPrincipal().toString();

        User user = userService.findUserByUsername(username);


        if (user == null){
            throw new ResultException(ResultEnum.USER_NAME_PWD_NULL);
        }



        return new SimpleAuthenticationInfo(user, username, getName());
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.debug("JWTRealm 授权方法执行");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();

        User currentUser = (User) subject.getPrincipal();

        String role = userService.findRoleByUsername(currentUser.getUsername());


        info.addRole(role);

        return info;
    }
}
